const user = require('./user');
const config = require('./config.js');

const getSystemInfo = () => {
    const res = wx.getSystemInfoSync();
    wx.setStorageSync(config.storage.keySystemInfo, res);
};

const checkSession = () =>
    new Promise((resolve, reject) => {
        wx.checkSession({
            success: (res) => {
                let needLogin = checkCSession();
                if (needLogin) {
                    console.log('checkSession success');
                    resolve(res);
                } else {
                    console.log('checkSession success overtime');
                    return login().then(resolve);
                }
            },
            fail: (res) => {
                console.log('checkSession fail');
                return login().then(resolve);
            }
        });
    });

const checkCSession = () => {
    const c_session = wx.getStorageSync(config.storage.keyLoginCode);
    return !!c_session;
};

const login = () =>
    new Promise((resolve, reject) => {
        wx.login({
            success: (res) => {
                console.log('wxapi login success');
                wx.setStorageSync(config.storage.keyLoginCode, res.code);
                return user.requestLogin()
                    .then(resolve);
            },
            fail: (res) => {
                console.log('wxapi login fail');
                reject(res);
            }
        });
    });


const getUserInfo = () =>
    new Promise((resolve, reject) => {
        wx.getUserInfo({
            success: function (res) {
                let userInfo = res.userInfo;
                wx.setStorageSync(config.storage.keyUserInfo, userInfo);
                user.saveUserInfo(userInfo);
                resolve(res);
            },
            fail: (res) => {
                reject(res);
            }
        })
    });

module.exports = {
    getSystemInfo,
    checkSession,
    getUserInfo
};